
layui.use(['layer', 'upload', 'form','table'], function() {
    var layer = layui.layer,
        form = layui.form,
    table = layui.table;

$(function(){

    var url = window.location.href;//获取当前浏览器的url
    index = url.indexOf("flag");//判断当前url是否有flag，如果有，说明是从A页面跳转而来的，就执行下面的程序

    if(index !=-1) {//由A页面跳转而来
        $("#makeNewSale").attr('disabled',true);
        $("#dec").attr('disabled',false);
        $("#inc").attr('disabled',false);
        $("#confirm").attr('disabled',false);
        $("#pendingOrder").attr('disabled',false);
        $("#chargeMoney").attr('disabled',false);
    }
        $.ajax({
            url: '/order/seekSession',
            dataType: 'json',
            success: function (data) {
                //空为false
                if (data.success == false) {
                    table.render({
                        elem: '#buyItems'
                        , title: '选购商品表'
                        , id: 'saleItemReload'
                        , totalRow: true
                        , height: 450
                        , cols: [[
                            {
                                field: 'clothesid',
                                title: '商品条码',
                                fixed: 'left',
                                sort: true,
                                totalRowText: '合计',
                                align: 'center'
                            }
                            , {field: 'clothesname', title: '商品名', align: 'center'}
                            , {field: 'num', title: '商品数量', sort: true, totalRow: true, align: 'center'}
                            , {field: 'price', title: '商品单价', sort: true, align: 'center'}
                            , {field: 'subtotal', title: '价格小计', totalRow: true, align: 'center'}
                            , {fixed: 'right', title: '操作', toolbar: '', align: 'center'}
                        ]]
                        , data: [//模拟数据，填充表格
                            {
                                "clothesid": "",
                                "clothesname": "",
                                "num": "",
                                "price": "",
                                "subtotal": "",
                            },
                            {
                                "clothesid": "",
                                "clothesname": "",
                                "num": "",
                                "price": "",
                                "subtotal": "",
                            },
                            {
                                "clothesid": "",
                                "clothesname": "",
                                "num": "",
                                "price": "",
                                "subtotal": "",
                            },
                            {
                                "clothesid": "",
                                "clothesname": "",
                                "num": "",
                                "price": "",
                                "subtotal": "",
                            },
                            {
                                "clothesid": "",
                                "clothesname": "",
                                "num": "",
                                "price": "",
                                "subtotal": "",
                            },
                            {
                                "clothesid": "",
                                "clothesname": "",
                                "num": "",
                                "price": "",
                                "subtotal": "",
                            },
                            {
                                "clothesid": "",
                                "clothesname": "",
                                "num": "",
                                "price": "",
                                "subtotal": "",
                            },
                            {
                                "clothesid": "",
                                "clothesname": "",
                                "num": "",
                                "price": "",
                                "subtotal": "",
                            },
                            {
                                "clothesid": "",
                                "clothesname": "",
                                "num": "",
                                "price": "",
                                "subtotal": "",
                            },
                            {
                                "clothesid": "",
                                "clothesname": "",
                                "num": "",
                                "price": "",
                                "subtotal": "",
                            }
                        ]
                    });
                } else if (data.success == true) {
                    table.render({
                        elem: '#buyItems'
                        /*                    ,toolbar:'#bar'*/
                        , url: 'sale/findOrderItem'
                        , title: '选购商品表'
                        , id: 'saleItemReload'
                        , totalRow: true
                        , height: 450
                        , cols: [[
                            {
                                field: 'clothesid',
                                title: '商品条码',
                                fixed: 'left',
                                sort: true,
                                totalRowText: '合计',
                                align: 'center'
                            }
                            , {field: 'clothesname', title: '商品名', align: 'center'}
                            , {field: 'num', title: '商品数量', sort: true, totalRow: true, align: 'center'}
                            , {field: 'price', title: '商品单价', sort: true, align: 'center'}
                            , {field: 'subtotal', title: '价格小计', totalRow: true, align: 'center'}
                            , {fixed: 'right', title: '操作', toolbar: '#barDemo', align: 'center'}
                        ]]
                    });
                }
            }

        });
});
    /**
     * 伪数据，用于在还没有数据添加进去时表格也会展示
     */

    table.render({
        elem:'#searchItems'
        ,title:'筛选商品表'
        ,cols:[[
            {field:'clothesName',title:'商品名称',align:'center'}
            ,{field:'clothesId',title:'商品编号',align:'center'}
            ,{field:'clothesSize', title:'商品尺码',align:'center'}
            ,{field:'clothesColor',title:'商品颜色',align:'center'}
            ,{field:'stock', title:'商品数量',sort:true,align:'center'}
        ]]
        ,data: [//模拟数据
            {
                "color":"",
                "size":"",
                "num":"",
            },
            {
                "color":"",
                "size":"",
                "num":"",
            },
            {
                "color":"",
                "size":"",
                "num":"",
            },
            {
                "color":"",
                "size":"",
                "num":"",
            },
            {
                "color":"",
                "size":"",
                "num":"",
            },
            {
                "color":"",
                "size":"",
                "num":"",
            },
            {
                "color":"",
                "size":"",
                "num":"",
            },
            {
                "color":"",
                "size":"",
                "num":"",
            },
            {
                "color":"",
                "size":"",
                "num":"",
            },
            {
                "color":"",
                "size":"",
                "num":"",
            }
        ]
    });
    /**
     * 通用表单验证
     */
/*    form.verify({
        username: [/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, '账号格式不正确'],
        pass: [/^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格']
    });*/

    /**
     * 通用表单提交(AJAX方式)
     * 添加销售记录
     */
    form.on('submit(confirm)', function(data) {
        var a='<%=session.getAttribute("ORDER_SESSION")%>';
        var b = $("#count").val();
        //var a = sessionStorage.getItem("ORDER_SESSION");
        console.log("Order为"+a);
        if (a==null){
            alert("尚未开启一次销售");
        }
        if (b<=0) {
                alert("数量必须输入大于0的整数");
                $('#count').isValid = false;
        }else {
            $.ajax({
                url: '/sale/addOrderItem',
                type: 'post',
                data: $(data.form).serialize(),
                dataType: 'json',
                success: function (data) {
                    $("#pendingOrder").attr('disabled',false);
                    $("#chargeMoney").attr('disabled',false);
                    $("#cancelOrder").attr('disabled',false);
                    /*                if(info.code === 1) {
                                        setTimeout(function() {
                                            location.href = info.url;
                                        }, 1000);
                                    }else{
                                        layer.msg(info.msg);
                                    }*/
/*                    console.log(data.num);
                    console.log(data);*/
                    table.render({
                        elem: '#buyItems'
                        , data: data
                        /*                    ,toolbar:'#bar'*/
                        , title: '选购商品表'
                        , totalRow: true
                        , height: 450
                        , cols: [[
                            {
                                field: 'clothesid',
                                title: '商品条码',
                                fixed: 'left',
                                sort: true,
                                totalRowText: '合计',
                                align: 'center'
                            }
                            , {field: 'clothesname', title: '商品名', align: 'center'}
                            , {field: 'num', title: '商品数量', sort: true, totalRow: true, align: 'center'}
                            , {field: 'price', title: '商品单价', sort: true, align: 'center'}
                            , {field: 'subtotal', title: '价格小计', totalRow: true, align: 'center'}
                            , {fixed: 'right', title: '操作', toolbar: '#barDemo',align: 'center'}
                        ]]
                    });
                    document.getElementById("addForm").reset();

                },
                error: function () {
                    alert("该商品不存在！");
                }
            });
        }
        return false;
    });


    table.on('tool(sale)', function (obj) {
        //注：tool是工具条事件名，demo是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            , layEvent = obj.event; //获得 lay-event 对应的值
        if (layEvent === 'edit') {
            layer.open({
                type: 1
                , title: '修改购买数量'
                , area: '450px'
                , closeBtn: false
                , btn: ['确认更改', '取消']
                , btnAlign: 'c'
                , content: '<form class="layui-form layui-form-pane" id="edit" style="margin-left: 100px line-height: 24px;" id="edit" ">' +
                    '        <div class="layui-form-item" style="margin-top: 20px">' +
                    '            <label class="layui-form-label">商品编号</label>' +
                    '            <div class="layui-input-inline">' +
                    '               <input id="clothesid" name="clothesid" lay-verify="number" class="layui-input" readonly="readonly" value="' + data.clothesid +'">' +
                    '            </div>' +
                    '          </div>' +
                    '        <div class="layui-form-item">' +
                    '            <label class="layui-form-label">数量:</label>' +
                    '            <div class="layui-input-inline">' +
                    '               <input type="text" id="num" name="num" lay-verify="number" oninput="value=value.replace(/[^\\d]/g,\'\')" class="layui-input" value="' + data.num +'">' +
                    '            </div>' +
                    '        </div>' +
                    '    </form>'
                , yes: function (index) {
                    var getData = new Object();
                    getData.clothesid = data.clothesid;
                    getData.num = $("#num").val();
                    if (!isNaN(getData.num)||parseInt(getData.num )<=0) {
                        alert("输入的数量应该是大于0的整数！")
                    }else {
                        $.ajax({
                            url: 'sale/editNum',
                            type: 'post',
                            data: getData,
                            dataType: 'json',
                            contentType: "application/x-www-form-urlencoded",
                            success: function (data) {
                                table.render({
                                    elem: '#buyItems'
                                    , data: data
                                    /*                    ,toolbar:'#bar'*/
                                    , title: '选购商品表'
                                    , totalRow: true
                                    , height: 450
                                    , cols: [[
                                        {
                                            field: 'clothesid',
                                            title: '商品条码',
                                            sort: true,
                                            totalRowText: '合计',
                                            align: 'center'
                                        }
                                        , {field: 'clothesname', title: '商品名', align: 'center'}
                                        , {field: 'num', title: '商品数量', sort: true, totalRow: true, align: 'center'}
                                        , {field: 'price', title: '商品单价', sort: true, align: 'center'}
                                        , {field: 'subtotal', title: '价格小计', totalRow: true, align: 'center'}
                                        , {fixed: 'right', title: '操作', toolbar: '#barDemo', align: 'center'}
                                    ]]
                                });
                            },
                            error: function () {
                                alert("编辑错误,请重新编写!");
                            }
                        });
                    }
                    layer.close(index);
                }
            });
        } else if (layEvent === 'del') {
            layer.alert('确定从购物清单中删除吗?', {
                closeBtn: 0    // 是否显示关闭按钮
                , anim: 6
                , btn: ['确定', '取消'] //按钮
                , yes: function (index) {
                    // obj.del();
                    // layer.close(index);
                    var getData = new Object();
                    getData.clothesId = data.clothesid;
                    $.ajax({
                        url: 'sale/delSaleItem',
                        type: 'post',
                        data: getData,
                        dataType: 'json',
                        success: function (data) {
                            table.render({
                                elem: '#buyItems'
                                ,data:data
                                /*                    ,toolbar:'#bar'*/
                                ,title:'选购商品表'
                                ,totalRow:true
                                ,height:450
                                ,cols:[[
                                    {field:'clothesid', title:'商品条码',  sort: true, totalRowText: '合计',align:'center'}
                                    ,{field:'clothesname', title:'商品名', align:'center'}
                                    ,{field:'num', title:'商品数量', sort:true,totalRow: true,align:'center'}
                                    ,{field:'price', title:'商品单价', sort:true, align:'center'}
                                    ,{field:'subtotal', title:'价格小计', totalRow: true, align:'center'}
                                    ,{fixed: 'right', title:'操作', toolbar: '#barDemo', align:'center'}
                                ]]
                            });
                        },
                        error: function () {
                            alert("删除错误,请重新操作!");
                        }
                    });
                    layer.close(index);
                }
            });
        }
});

});
//回车键触发提交一条销售记录
/*    $(document).keydown(function(event) {
        if(event.keyCode == 13) {
            $("#confirm").trigger("click");
        }
    })*/
    //shift键开启一次销售
    $(document).keydown(function(event) {
        if(event.keyCode == 16) {
            $("#makeNewSale").trigger("click");
        }
    })
//F1挂单
$(document).keydown(function(event) {
    if(event.keyCode == 112) {
        $("#pendingOrder").trigger("click");
    }
})
//F2全单取消
$(document).keydown(function(event) {
    if(event.keyCode == 113) {
        $("#cancelOrder").trigger("click");
    }
})



/*    $('#btn_save').click(function () {
        var data = [];
        $('.box').each(function () {
            var box = {};
            box['id'] = $(this).attr('dataId');
            box['text'] = $(this).find('.content').text();
            box['color'] = $(this).find('.bg').css('background-color');
            box['height'] = $(this).height();
            box['width'] = $(this).width();
            box['pageX'] = $(this).position().left;
            box['pageY'] = $(this).position().top;
            console.dir(box);
            data.push(box);

        });
        $("passdata").val(data);
        $("form").submit();
    });*/

/**
 * 开启一次新销售
 */
    function makeNewSale() {

    $.ajax({
        url: '/sale/makeNewSale',
        type: 'post',
        dataType: 'JSON',
        success: function (data) {
            alert(data.msg);
            $("#makeNewSale").attr('disabled',true);
            $("#dec").attr('disabled',false);
            $("#inc").attr('disabled',false);
            $("#confirm").attr('disabled',false);
/*            $("#pendingOrder").attr('disabled',false);
            $("#chargeMoney").attr('disabled',false);
            $("#cancelOrder").attr('disabled',false);*/
        }
    })
}

/**
 * 挂单
 */
    function pendingOrder() {
    layer.open({
        type: 1
        , title: '请输入顾客手机号码'
        , area: '450px'
        , closeBtn: false
        , btn: ['确认', '取消']
        , btnAlign: 'c'
        , content: '<form class="layui-form layui-form-pane" id="edit" style="margin-left: 50px; margin-top:20px" id="edit" ">' +
            '        <div class="layui-form-item">' +
            '            <label class="layui-form-label">顾客手机号码:</label>' +
            '            <div class="layui-input-inline">' +
            '               <input type="text" id="phone" name="phone" oninput="value=value.replace(/[^\\d]/g,\'\')" lay-verify="phone" class="layui-input">' +
            '            </div>' +
            '        </div>' +
            '    </form>'
        , yes: function (index) {
            var getData = new Object();
            getData.phone = $("#phone").val();
        $.ajax({
            url:'/sale/pendingOrder',
            type:'post',
            data: getData,
            dataType:'JSON',
            success:function(data){
/*                layui.table.reload("saleItemReload");*/
                alert(data.msg);
                window.location.href="/toSalePage";
/*                $("#makeNewSale").attr('disabled',false);
                $("#dec").attr('disabled',true);
                $("#inc").attr('disabled',true);
                $("#confirm").attr('disabled',true);
                $("#pendingOrder").attr('disabled',true);
                $("#chargeMoney").attr('disabled',true);
                $("#cancelOrder").attr('disabled',true);*/
            }
        });
            layer.close(index);
        }
    })
    }

/**
 * 全单取消
 */
function cancelOrder(){
        $.ajax({
            url:'/sale/cancelOrder',
            type:'post',
            dataType:'JSON',
            success:function (data) {
                if (data.success) {
/*                    layui.table.reload("saleItemReload");*/
                    alert(data.msg);
                    window.location.reload(true);
/*                    $("#makeNewSale").attr('disabled',false);
                    $("#dec").attr('disabled',true);
                    $("#inc").attr('disabled',true);
                    $("#confirm").attr('disabled',true);
                    $("#pendingOrder").attr('disabled',true);
                    $("#chargeMoney").attr('disabled',true);
                    $("#cancelOrder").attr('disabled',true);*/

                }
            },
            error:function () {
                alert("取消出错！");
            }
        })
    }

/**
 * 搜索同种商品的指定尺码的库存
 */
function searchStock(){
    $.ajax({
        url:'/stock/searchStock',
        data: {
            "clothesId":$("#enterId").val(),
            "clothesSize":$('#clothesSize option:selected').text()
        },
        type:'post',
        dataType:'json',
        contentType: "application/x-www-form-urlencoded",
        success:function (data) {
            layui.table.render({
                elem: '#searchItems'
                ,data:data
                , title: '筛选商品表'
                , cols: [[
                    {field: 'clothesName', title: '商品名称', align: 'center'}
                    , {field: 'clothesId', title: '商品编号', align: 'center'}
                    , {field: 'clothesSize', title: '商品尺码', align: 'center'}
                    , {field: 'clothesColor', title: '商品颜色', align: 'center'}
                    , {field: 'stock', title: '商品数量', sort: true, align: 'center'}
                ]]
            })
        },
        error:function () {
            alert("查询出错！");
        }
    })
}



/**
 * 判断session的订单清单是否为空
 */
/*
var seekSession = function() {
    var a = 1;
    $.ajax({
        url:'/order/seekSession',
        dataType:'json',
        success:function (data) {
            //空为false
            if (data.success==false) {
                alert("session为空!");
                a = null;
            }
        }
    });
    return a;
};
*/

